from markdown.api_transform import *

"""
Author: Gaoqiang Du
Description：Markdown文件解析器，以生成器作协程的形式逐行解析数据
Time: 2022/4/17 12:30
"""

req_methods_str = "POST|GET|PUT|DELETE"


def get_title_headers(line: str):
    if line and line[0] == line[-1] == "|":
        headers = re.split(" \| ", line[1:-1])

        return [h.strip() for h in headers]
    return []


def get_title_body_line(line: str, header_len: int):
    if line and line[0] == line[-1] == "|":
        body_line = re.split(" \| ", line[1:-1])
        if len(body_line) == header_len:
            if not body_line[0].strip().startswith(":--"):
                return [i.strip() for i in body_line]
    return []


def check_line():
    # 检查此行应该归于什么属性
    line, code_line = "", False
    while 1:
        prop = ""
        if line:
            if code_line:
                if line.startswith("```"):
                    # 代码块逻辑，需要标记整个代码块
                    code_line = not code_line
            elif line.startswith("|") and line.endswith("|"):
                prop = ""
            elif re.search("请求方式|" + req_methods_str, line):
                prop = "req_method"
            elif re.search("请求参数|query|请求数据", line):
                prop = "req_params"
            elif re.search("返回数据", line):
                prop = "res_json"
            elif re.search("返回示例", line):
                prop = "res_example"
            elif line.startswith("```"):
                # 代码块逻辑，需要标记整个代码块
                code_line = not code_line

        line = (yield prop).strip()


def get_title():
    title = line = ""
    while not title:
        if line.startswith("#"):
            title = line[2:].strip()

        line = yield bool(title), title


def find_description():
    line = description = ""
    while not line.startswith("##"):
        if line and not line.strip().startswith("# "):
            description += "" if line.startswith("##") else ("\n" + line)

        line = yield line.startswith("##"), description.strip()


def find_req_method():
    req_method = line = ""
    while not req_method:
        req_methods = re.findall(req_methods_str, line.upper())
        if req_methods:
            req_method = req_methods[0]

        line = yield bool(req_method), req_method.lower()


def find_req_params():
    line = ""
    title_headers = []
    params = []
    while 1:
        if not title_headers:
            title_headers = format_table_headers(get_title_headers(line))
        else:
            body_line = get_title_body_line(line, len(title_headers))
            if body_line:
                params.append(format_param_item(body_line, title_headers))
            else:
                if not line.startswith("|"):
                    yield True, params
                    break

        line = yield False, params


def find_res_params():
    line = ""
    title_headers = []
    params = []
    while 1:
        if not title_headers:
            title_headers = format_table_headers(get_title_headers(line))
        else:
            body_line = get_title_body_line(line, len(title_headers))
            if body_line:
                params.append(format_res_item(body_line, title_headers))
            else:
                if not line.startswith("|"):
                    yield True, params
                    break

        line = yield False, params


def find_res_example():
    line = example = ""
    code_line = False
    while not example or code_line:
        if line.startswith("```"):
            code_line = not code_line
        elif code_line:
            example += line + "\n"

        line = yield (example and not code_line), example.strip()
